package com.twu.biblioteca.menu;

import java.io.IOException;
import java.util.HashMap;

public class Menu {
    private static final int OPTION_EXIT = 0;
    private static final String WELCOME = "Welcome, select an option or 0 to exit:";

    private final HashMap<Integer, MenuItem> menuItems;
    private final MenuInputReader reader;

    public Menu(HashMap<Integer, MenuItem> menuItems, MenuInputReader reader)
    {
        this.menuItems = menuItems;
        this.reader = reader;
    }

    public void run() throws IOException
    {
        try
        {
            String mainMenu = buildMainMenuString();
            System.out.println(mainMenu);
            int option = reader.readNumber();
            if(option == OPTION_EXIT) return;
            MenuItem menuItem = getMenuItem(option);
            String output = menuItem.toString();
            System.out.println(output);
            menuItem.run();
        }
        catch(InvalidOptionException e)
        {
            System.out.println(e.getMessage());
        }
        this.run();
    }

    public MenuItem getMenuItem(int option) throws InvalidOptionException
    {
        MenuItem menuItem = menuItems.get(option);
        if(menuItem == null)
        {
            throw new InvalidOptionException();
        }
        else
        {
            return menuItem;
        }
    }

    private String buildMainMenuString()
    {
        StringBuilder sb = new StringBuilder();
        sb.append("\n" + WELCOME + "\n");
        for (int key : menuItems.keySet())
        {
            MenuItem menuItem = menuItems.get(key);
            sb.append(key + "\t" + menuItem.title + "\n");
        }
        return sb.toString();
    }
}
